package dao;

import java.io.IOException;
import java.text.MessageFormat;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 * 鍒嗛〉鏍囩
 * list?curpage=1&pagesize=10&city=鏍床&sex=甯呭摜
 * @author Administrator
 *
 */
public class PageTag extends SimpleTagSupport {
	private String url;//URL
    private int curpage;// 当前页
    private int pagesize;// 页大小
    private int total;// 总记录数
   
    public void setUrl(String url) {
         this.url = url;
    }
   
    public String getUrl() {
         return url;
    }

    public int getCurpage() {
         return curpage;
    }

    public void setCurpage(int curpage) {
         this.curpage = curpage;
    }

    public int getPagesize() {
         return pagesize;
    }

    public void setPagesize(int pagesize) {
         this.pagesize = pagesize;
    }

    public int getTotal() {
         return total;
    }

    public void setTotal(int total) {
         this.total = total;
    }
   
    @Override
    public void doTag() throws JspException, IOException {
         super.doTag();
         //计算总页数
         int pages = (total - 1) / pagesize + 1;
        
         String href = "<a href=\"{0}?curpage={1}&pagesize={2}\">{3}</a> ";
         //第一页
         String first = MessageFormat.format(href, url, 1, pagesize, "第一页");
         //上一页
         String pre = null;
         if(curpage == 1){
              pre = "<a>上一页</a> ";
         }else{
              pre = MessageFormat.format(href, url, curpage - 1, pagesize, "上一页");
         }
         //下一页
         String next = null;
         if(curpage == pages){
              next = "<a>下一页</a> ";
         }else{
              next = MessageFormat.format(href, url, curpage + 1, pagesize, "下一页");
         }
         //最后一页
         String last = MessageFormat.format(href, url, pages, pagesize, "最后一页");
         //其他信息
         String other = select(pages) + "/" + pages
                   + "每页显示" + pagesize
                   + "条记录  共" + total +"条记录";
         //拼凑成一个完整的字符串
         String link = first + pre + next + last + other;
         JspWriter out = getJspContext().getOut();
         out.print(link);
    }

    private String select(int pages){
         String content = "<script> function c(s){" +
                   "var v = s.value;" +
                   "location = '" + url +"?curpage=' + v + '&pagesize=" + pagesize+"';" +
                   "} </script>";
        
         String p = "<option value={0} {1}>{0}</option>";
         String options = "";
         for(int i = 1; i <= pages; i ++){
              options += MessageFormat.format(p, i,
                        curpage == i ? "selected" : "");
         }
         return content + " <select onchange='c(this)'>" + options + "</select> ";
    }
}	









